import re, random
from flask import Blueprint, request, jsonify
from conf.comm import sqlalchemy_context
from database import *
import json, os, uuid
from werkzeug.security import generate_password_hash
from conf.comm import send_message
from utils.redisconn import RedisCon

# 蓝图初始化


bp_users = Blueprint('users', __name__)


# 注册功能
@bp_users.route('/reg', methods=['POST'])
@sqlalchemy_context()
def reg():
    data = request.data
    # 获取用户输入
    if not data:
        data = request.form
    else:
        data = json.loads(data)
    # 有效性验证
    reg = re.match('^1[3-9]\d{9}$', str(data['mobile']))
    if not reg:
        return jsonify({"code": 10012, 'mes': '手机号不合法'})

    # 构造user
    try:
        user = User(username=data['username'], password=generate_password_hash(data['password']), mobile=data['mobile'])
        db.session.add(user)
        db.session.commit()
        return jsonify({'code': 200})
    except:
        return jsonify({'code': 10010})


# 发送验证码
@bp_users.route('/sendsms', methods=['POST'])
def sendsms():
    # 传递手机号
    data = request.data
    if data:
        data = json.loads(request.data)
    else:
        data = request.form
    mobile = data['mobile']

    if not mobile:
        return jsonify({'code': 20010, 'mes': '必须输入手机号'})

    # 生成验证码
    code = random.randint(1000, 9999)
    # 调用短信接口
    flag = send_message(mobile, code, 1)
    if flag:
        # 发送成功，存入redis
        r = RedisCon()
        r.set_str(mobile, code, 30)
        # 返回结果（验证码）
        return jsonify({'code': 200, 'smscode': code})
    else:
        return jsonify({'code': 20011, 'mes': '发送失败，请重试'})


from utils.myjwt import myjwt


# 登录功能
@bp_users.route('/login', methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form

    mobile = data['mobile']
    code = data['code']

    r = RedisCon()
    hcode = r.get_str(mobile)
    if hcode:
        if int(code) == int(hcode):
            user = User.query.filter_by(mobile=mobile).first()
            if not user:
                user = User(username=mobile, mobile=mobile)
                db.session.add(user)
                db.session.commit()
            # 清除
            r.del_str(mobile)
            token = myjwt.jwt_encode({'data': {'username': user.username, 'userid': user.id}})
            return jsonify({'code': 200, 'userid': user.id, 'username': user.username, 'token': token})
        else:
            return jsonify({'code': 20012, 'mes': '验证码错误'})


# 返回用户信息接口
@bp_users.route('/getuserinfo')
def getuserinfo():
    # 数据库查询返回
    id = request.args.get('userid')
    user = User.query.filter_by(id=id).first()
    dict = {}
    dict['id'] = user.id
    dict['username'] = user.username
    dict['mobile'] = user.mobile
    return jsonify({'code': 200, 'dict': dict})


@bp_users.before_request
def before_request():
    # list: ['', '', '']
    # if request.path not in list:
    # 获取token
    try:
        token = request.headers['Token']
    except:
        return jsonify({"code": 403, 'mes': '请传递token'})
        # 解密重新对比token
    newtoken = myjwt.jwt_decode(token)
    if newtoken and myjwt.check(token, newtoken):
        pass
    else:
        return jsonify({"code": 403, 'mes': '无权访问'})


# 头像上传
@bp_users.route('/upload', methods=['POST', 'GET'])
def upload():
    # 获取文件
    file = request.files['file']
    # 上传到upload文件夹
    # 解决文件名被覆盖的问题
    # 1.文件重命名   文件名.后缀
    # 获取文件后缀
    filetext = os.path.splitext(file.filename)[1]
    newfile = uuid.uuid4().hex + filetext
    # 2.在upload下面建立一个文件夹，专业存，文件夹的名字为userid
    userid = request.form.get('userid')
    # 根据userid创建文件夹
    # 判断此用户文件夹是否存在，存在直接写文件，不存在创建
    path = './static/upload/' + str(userid)
    # 不存在创建文件
    if not os.path.exists(path):
        os.mkdir(path)
    file.save(os.path.join(path, newfile))
    return jsonify({"code": 200, 'filename': newfile})